package com.qqt.csr.common.sensitiveword;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.util.List;

@Slf4j
@Component
public class SensitiveWordReplaceHandler {

    /**
     * 按规则替换敏感词部分
     *
     * @param text
     * @param sensitiveWordMsgList
     * @return
     */
    public String replace(String text, List<SensitiveWordMsg> sensitiveWordMsgList) {
        if (StringUtils.isBlank(text) || CollectionUtils.isEmpty(sensitiveWordMsgList)) {
            return text;
        }

        return doReplace(text, sensitiveWordMsgList);
    }

    /**
     * 替换
     *
     * @param target   目标字符串
     * @param wordList 敏感词列表
     * @return 结果
     */
    private String doReplace(String target, List<SensitiveWordMsg> wordList) {
        StringBuilder stringBuilder = new StringBuilder();
        // 注意边界
        int startIndex = 0;
        char[] rawChars = target.toCharArray();

        for (SensitiveWordMsg wordInfo : wordList) {
            // 脱敏的左边
            if (startIndex < wordInfo.getSidx()) {
                stringBuilder.append(rawChars, startIndex, wordInfo.getSidx() - startIndex);
            }

            // 脱敏部分
            SensitiveWordShowTypeEnum wordShowTypeEnum = SensitiveWordShowTypeEnum.match(wordInfo.getShowType());
            String replaceWord = wordShowTypeEnum.getSensitiveWordDisplay()
                    .format(rawChars, wordInfo.getSidx(), wordInfo.getEidx());
            stringBuilder.append(replaceWord);

            // 更新结尾
            startIndex = Math.max(startIndex, wordInfo.getEidx());
        }

        // 最后部分
        if (startIndex < rawChars.length) {
            stringBuilder.append(rawChars, startIndex, rawChars.length - startIndex);
        }
        return stringBuilder.toString();
    }
}
